//
//  SDTabbarController.m
//  ShandongNews
//
//  Created by zengyuan on 10/3/14.
//  Copyright (c) 2014 zengyuan. All rights reserved.
//

#import "Config.h"

#import "AWTabBarController.h"
#import "AppDelegate.h"
#import "MLNavigationController.h"
@interface AWTabBarController ()

@end

@implementation AWTabBarController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //    self.tabBar.translucent=NO;
    if (OSVersionIsAtLeastiOS7) {
        self.tabBar.barTintColor=[UIColor whiteColor];
    }else{
        self.tabBar.tintColor=[UIColor whiteColor];
        
        UIEdgeInsets insets = UIEdgeInsetsMake(5, 5, 5, 5);
        UIImage *streImage = [[UIImage imageNamed:@"white"] resizableImageWithCapInsets:insets];
        [self.tabBar setSelectionIndicatorImage:streImage];
        [self.tabBar setBackgroundImage:streImage];
    }
	// Do any additional setup after loading the view.
    
    if (!OSVersionIsAtLeastiOS6) {
        HorizonLine *line =[[HorizonLine alloc]initWithFrame:CGRectMake(0, 0, self.tabBar.frame.size.width, 0.5)];
//        [line setLineColor:LISTCELL_LINECOLOR];
        [self.tabBar addSubview:line];
    }
    
//    [self setItems];
}

-(UIButton *)itemBtn:(int)index{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:CGRectMake(0, 0, 30, 44)];
    [btn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    btn.tag=100+index;
    [btn addTarget:self action:@selector(changeItem:) forControlEvents:UIControlEventTouchUpInside];
    return btn;
    
}

-(void)setBtn:(UIButton *)btn Image:(NSString *)imagename{
    [btn setImage:[UIImage imageNamed:imagename] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed: [NSString stringWithFormat:@"%@-h",imagename] ]
    forState:UIControlStateSelected];

}



-(UILabel *)itemLabel:(NSInteger)index{
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 30, 10)];
    label.font=[UIFont systemFontOfSize:10];
    label.numberOfLines=0;
    label.textAlignment=NSTextAlignmentCenter;
    label.highlightedTextColor=[UIColor redColor];
    label.textColor=[UIColor darkGrayColor];
    label.tag=200+index;

    return label;
}


-(void)setItemSelected:(NSInteger)index{
    for (int i=0; i<self.viewControllers.count; i++) {
        UIButton *btn =(UIButton *)[self.tabBar viewWithTag:100+i];
        UILabel *label = (UILabel *)[self.tabBar viewWithTag:200+i];

        if (i==index) {
            [btn setSelected:YES];
            [label setHighlighted:YES];
        }else{
            [btn setSelected:NO];
            [label setHighlighted:NO];
        }
    }
    

}

-(void)setItems{
    
    UIColor*  TAB_THEMECOLOR = NAV_COLOR;
    UIColor*  TAB_NORMALCOLOR = RGB(142, 142, 146);

    //device
    UIViewController *viewcontroller0=[self.viewControllers objectAtIndex:0];

    viewcontroller0.tabBarItem.image = [[UIImage imageNamed:@"home"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        viewcontroller0.tabBarItem.selectedImage = [[UIImage imageNamed:@"home_h"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
 
    [viewcontroller0.tabBarItem setTitle:@"我的设备"];
    
    
    //find
    UIViewController *viewcontroller1=[self.viewControllers objectAtIndex:1];
        viewcontroller1.tabBarItem.image = [[UIImage imageNamed:@"find"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        viewcontroller1.tabBarItem.selectedImage = [[UIImage imageNamed:@"find_h"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

    [viewcontroller1.tabBarItem setTitle:@"发现"];
    
//    //产品体验
//    UIViewController *viewcontroller2=[self.viewControllers objectAtIndex:2];
//        viewcontroller2.tabBarItem.image = [[UIImage imageNamed:@"me"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//        viewcontroller2.tabBarItem.selectedImage = [[UIImage imageNamed:@"me_h"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//
//    [viewcontroller2.tabBarItem setTitle:@"产品体验馆"];
//    

    //我的
    UIViewController *viewcontroller2=[self.viewControllers objectAtIndex:2];
        viewcontroller2.tabBarItem.image = [[UIImage imageNamed:@"me"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        viewcontroller2.tabBarItem.selectedImage = [[UIImage imageNamed:@"me_h"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

    [viewcontroller2.tabBarItem setTitle:@"我的"];
 
    for (int i=0; i<self.viewControllers.count; i++) {
        UIViewController *viewcontroller=[self.viewControllers objectAtIndex:i];

        viewcontroller.tabBarItem.tag=100+i;

        
        [viewcontroller.tabBarItem setTitlePositionAdjustment:UIOffsetMake(0,-3)];
        
        [viewcontroller.tabBarItem setTitleTextAttributes:
         [NSDictionary dictionaryWithObjectsAndKeys:TAB_THEMECOLOR,NSForegroundColorAttributeName,  nil] forState:UIControlStateHighlighted];
        [viewcontroller.tabBarItem setTitleTextAttributes:
         [NSDictionary dictionaryWithObjectsAndKeys:TAB_NORMALCOLOR,NSForegroundColorAttributeName,  nil] forState:UIControlStateNormal];

    }
    //msg
    [self addUnreadStateAlert];
    //circle
    [self addNewNoticeCircleAlert];
    //topic
    [self addNewTopicAlert];
    
}


/**
 *  新话题提醒
 */
-(void)addNewTopicAlert{
    
    CGRect rec = [self frameForTabInTabBar:self.tabBar withIndex:3];

    newTopicAlertLabel = [[UILabel alloc]initWithFrame:CGRectMake(rec.origin.x + rec.size.width/2+12, 2, 10, 10)];
    [self.tabBar addSubview:newTopicAlertLabel];
    newTopicAlertLabel.backgroundColor = NOTICE_RED;
    newTopicAlertLabel.layer.cornerRadius=newTopicAlertLabel.frame.size.width/2;
    newTopicAlertLabel.layer.masksToBounds=YES;
    newTopicAlertLabel.hidden=YES;
 }

-(void)freshNewTopic:(BOOL)hide{
    newTopicAlertLabel.hidden=hide;
}


/**
 *  未读警告
 */
-(void)addUnreadStateAlert{
    CGRect rec = [self frameForTabInTabBar:self.tabBar withIndex:1];

    unreadStateLabel = [[UILabel alloc]initWithFrame:CGRectMake(rec.origin.x + rec.size.width/2+5, 2, 18, 18)];
    [self.tabBar addSubview:unreadStateLabel];
    unreadStateLabel.backgroundColor = NOTICE_RED;
    unreadStateLabel.textColor = [UIColor whiteColor];
    unreadStateLabel.layer.cornerRadius=9;
    unreadStateLabel.layer.masksToBounds=YES;
    unreadStateLabel.font = [UIFont systemFontOfSize:12];
    unreadStateLabel.hidden=YES;
    unreadStateLabel.textAlignment=NSTextAlignmentCenter;
}

-(void)freshUnreadAlert:(NSInteger)number{
    if (number <= 0) {
        unreadStateLabel.hidden=YES;
        return;
    }
    
    unreadStateLabel.hidden=NO;
    if (number>999) {
        unreadStateLabel.text = @"999+";
    }
    unreadStateLabel.text = [NSString stringWithFormat:@"%ld", (long)number];

    CGRect rec = unreadStateLabel.frame;
    rec.size.width = 18 + (unreadStateLabel.text.length-1)*2;
    unreadStateLabel.frame=rec;

}


/**
 *  圈子未读警告
 */
-(void)addNewNoticeCircleAlert{
    CGRect rec = [self frameForTabInTabBar:self.tabBar withIndex:2];
    
    newnoticeCircleLabel = [[UILabel alloc]initWithFrame:CGRectMake(rec.origin.x + rec.size.width/2+5, 2, 18, 18)];
    [self.tabBar addSubview:newnoticeCircleLabel];
    newnoticeCircleLabel.backgroundColor = NOTICE_RED;
    newnoticeCircleLabel.textColor = [UIColor whiteColor];
    newnoticeCircleLabel.layer.cornerRadius=9;
    newnoticeCircleLabel.layer.masksToBounds=YES;
    newnoticeCircleLabel.font = [UIFont systemFontOfSize:12];
    newnoticeCircleLabel.hidden=YES;
    newnoticeCircleLabel.textAlignment=NSTextAlignmentCenter;
}

-(void)freshCircleNewNoticeAlert:(NSInteger)number{
    
    if (number <= 0) {
        newnoticeCircleLabel.hidden=YES;
        return;
    }
    
    newnoticeCircleLabel.hidden=NO;
    if (number>999) {
        newnoticeCircleLabel.text = @"999+";
    }
    newnoticeCircleLabel.text = [NSString stringWithFormat:@"%ld", (long)number];
    
    CGRect rec = newnoticeCircleLabel.frame;
    rec.size.width = 18 + (newnoticeCircleLabel.text.length-1)*2;
    newnoticeCircleLabel.frame=rec;
    
}


-(void)changeItem:(UIButton *)btn{
    NSInteger index = btn.tag-100;
    [self setItemSelected:index];
    [self setSelectedIndex:index];
}


/*
-(void)showHighlighted:(UIButton *)btn{
    NSLog(@"ficki");
    [self setQRCodeTabimg:@"二维码灰"];
    [self.tabBar bringSubviewToFront:btn];
    
    //    [self setSelectedIndex:2];

}
*/
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item{

}

-(void)setQRCodeTabimg:(NSString *)imgname{
    UIViewController *viewcontroller2=[self.viewControllers objectAtIndex:2];
    
    if (OSVersionIsAtLeastiOS7) {
        [viewcontroller2.tabBarItem setImage:
         [[UIImage imageNamed:imgname] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    }else{
        [viewcontroller2.tabBarItem setFinishedSelectedImage:[UIImage imageNamed:imgname] withFinishedUnselectedImage:[UIImage imageNamed:imgname]];
        
    }
}

- (CGRect)frameForTabInTabBar:(UITabBar*)tabBar withIndex:(NSUInteger)index
{
    NSMutableArray *tabBarItems = [NSMutableArray arrayWithCapacity:[tabBar.items count]];
    for (UIView *view in tabBar.subviews) {
        if ([view isKindOfClass:NSClassFromString(@"UITabBarButton")] && [view respondsToSelector:@selector(frame)]) {
            // check for the selector -frame to prevent crashes in the very unlikely case that in the future
            // objects thar don't implement -frame can be subViews of an UIView
            [tabBarItems addObject:view];
        }
    }
    if ([tabBarItems count] == 0) {
        // no tabBarItems means either no UITabBarButtons were in the subView, or none responded to -frame
        // return CGRectZero to indicate that we couldn't figure out the frame
        return CGRectZero;
    }
    
    // sort by origin.x of the frame because the items are not necessarily in the correct order
    [tabBarItems sortUsingComparator:^NSComparisonResult(UIView *view1, UIView *view2) {
        if (view1.frame.origin.x < view2.frame.origin.x) {
            return NSOrderedAscending;
        }
        if (view1.frame.origin.x > view2.frame.origin.x) {
            return NSOrderedDescending;
        }
        NSAssert(NO, @"%@ and %@ share the same origin.x. This should never happen and indicates a substantial change in the framework that renders this method useless.", view1, view2);
        return NSOrderedSame;
    }];
    
    CGRect frame = CGRectZero;
    if (index < [tabBarItems count]) {
        // viewController is in a regular tab
        UIView *tabView = tabBarItems[index];
        if ([tabView respondsToSelector:@selector(frame)]) {
            frame = tabView.frame;
        }
    }
    else {
        // our target viewController is inside the "more" tab
        UIView *tabView = [tabBarItems lastObject];
        if ([tabView respondsToSelector:@selector(frame)]) {
            frame = tabView.frame;
        }
    }
    return frame;
}

@end
